<!DOCTYPE html>
<html>
<head>
    <title>用户管理</title>
    <meta charset="utf-8">
    <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon"/>
    <link rel="stylesheet" href="/js/bootstrap/css/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="/css/jsherp.css"/>
    <script type="text/javascript" src="/js/jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="/js/colorbox/jquery.colorbox-min.js"></script>
    <script type="text/javascript" src="/js/colorbox/colorboxSet.js"></script>
    <link href="/js/colorbox/colorbox.css" rel="stylesheet" type="text/css"/>
    <link rel="stylesheet" type="text/css" href="/js/easyui/themes/default/easyui.css"/>
    <link rel="stylesheet" type="text/css" href="/js/easyui/themes/icon.css"/>
    <link type="text/css" rel="stylesheet" href="/css/common.css"/>
    <script type="text/javascript" src="/js/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="/js/common/common.js"></script>
</head>
<body>
<!-- 数据显示table -->
<div id="tablePanel" class="easyui-panel" data-options="fit:true" style="padding:1px;top:300px;" title="用户列表" iconCls="icon-list">
    <div class="box-body form-inline">
        <div class="form-group">
            <label class="control-label">登录名称：</label>
            <div class="control-inline">
                <input type="text" id="searchLoginName" name="searchLoginName" value="" maxlength="100" class="easyui-textbox width-90"/>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label">用户姓名：</label>
            <div class="control-inline">
                <input type="text" id="searchUsername" name="searchUsername" value="" maxlength="100" class="easyui-textbox width-90"/>
            </div>
        </div>
        <div class="form-group">
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-search" id="searchBtn">查询</a>&nbsp;
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-redo" id="searchResetBtn">重置</a>
            <a id="btnSetRole" class='easyui-linkbutton iframe iframe_LargeForm' href='#' title='分配角色'>分配角色</a>
            <a id="btnSetDepart" class='easyui-linkbutton iframe iframe_LargeForm' href='#' title='分配仓库'>分配仓库</a>
            <a id="btnSetCustomer" class='easyui-linkbutton iframe iframe_LargeForm' href='#' title='分配客户'>分配客户</a>
        </div>
    </div>
    <table id="tableData" style="top:300px;border-bottom-color:#FFFFFF"></table>
</div>

<div id="userDlg" class="easyui-dialog" style="width:380px;padding:10px 20px"
     closed="true" buttons="#dlg-buttons" modal="true" collapsible="false" closable="true">
    <form id="usernameFM" method="post" novalidate>
        <table>
            <tr>
                <td>登录名称</td>
                <td style="padding:5px">
                    <input name="loginName" id="loginName" class="easyui-textbox"
                           data-options="required:true,validType:'length[2,15]'" style="width: 120px;"/>
                    初始密码：123456
                </td>
            </tr>
            <tr>
                <td>
                    用户姓名
                </td>
                <td style="padding:5px">
                    <input name="username" id="username" class="easyui-textbox"
                           data-options="required:true,validType:'length[2,30]'" style="width: 230px;"/>
                </td>
            </tr>
            <tr>
                <td>部门</td>
                <td style="padding:5px">
                    <input name="orgAbr" id="orgAbr" class="easyui-textbox" readonly style="width: 120px;"/>
                    <a href="javascript:void(0)" class="l-btn l-btn-plain" group="" id="lookForSelectOrganization">
                        <span class="l-btn-left"><span class="l-btn-text icon-search l-btn-icon-left" style="height:20px;"></span></span></a>
                    <input name="orgaId" id="orgaId" type="hidden"/>
                    <input name="selectType" id="selectType" type="hidden"/>
                    <input name="orgaUserRelId" id="orgaUserRelId" type="hidden"/>
                    <!--一个兼容input框，没有实际用处，但是必须存在-->
                    <input name="id" id="id" type="hidden"/>
                </td>
            </tr>
            <tr>
                <td>
                    职位
                </td>
                <td style="padding:5px">
                    <input name="position" id="position" class="easyui-textbox" style="width: 230px;"/>
                </td>
            </tr>
            <tr>
                <td>
                    联系电话
                </td>
                <td style="padding:5px">
                    <input name="phonenum" id="phonenum" class="easyui-numberbox" style="width: 230px;"/>
                </td>
            </tr>
            <tr>
                <td>
                    电子邮箱
                </td>
                <td style="padding:5px">
                    <input name="email" id="email" class="easyui-textbox" data-options="validType:'email'" style="width: 230px;"/>
                </td>
            </tr>
            <tr>
                <td>
                    用户排序
                </td>
                <td style="padding:5px">
                    <input name="userBlngOrgaDsplSeq" id="userBlngOrgaDsplSeq" class="easyui-textbox" style="width: 230px;"/>
                </td>
            </tr>
            <tr>
                <td>
                    描述
                </td>
                <td style="padding:5px">
                    <textarea name="description" id="description" class="easyui-textbox" data-options="multiline:true" style="width: 230px;height: 40px;"></textarea>
                </td>
            </tr>
        </table>
    </form>
</div>
<div id="dlg-buttons">
    <a href="javascript:void(0)" id="resetPwd" class="easyui-linkbutton" iconCls="icon-redo">重置密码</a>
    <a href="javascript:void(0)" id="saveusername" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
    <a href="javascript:void(0)" id="cancelusername" class="easyui-linkbutton" iconCls="icon-cancel"
       onclick="javascript:$('#userDlg').dialog('close')">取消</a>
</div>
<div id="forSelectOrganizationDlg" class="easyui-dialog" style="width:380px;padding:10px 20px"
     closed="true" modal="true" cache="false" collapsible="false" closable="true">
</div>
<script type="text/javascript">
    //初始化界面
    $(function () {
        initConfig();
        initTableData();
        ininPager();
    });

    //初始化配置
    function initConfig() {
        $("#btnSetDepart").hide();
        $("#btnSetCustomer").hide();
        var config = getSystemConfig();
        if(config) {
            if(config.depotFlag == "1") {
                $("#btnSetDepart").show();
            }
            if(config.customerFlag == "1") {
                $("#btnSetCustomer").show();
            }
        }
    }

    //初始化表格数据
    function initTableData() {
        $('#tableData').datagrid({
            height: heightInfo,
            nowrap: false,
            rownumbers: false,
            //动画效果
            animate: false,
            //选中单行
            singleSelect: true,
            collapsible: false,
            pagination: true,
            //交替出现背景
            striped: true,
            pageSize: initPageSize,
            pageList: initPageNum,
            columns: [[
                {field: 'id', width: 35, align: "center", checkbox:true},
                {
                    title: '操作', field: 'isystem', align: "center", width: 80, formatter: function (value, rec, index) {
                        var str = '';
                        if(rec.loginame != "jsh") {
                            str += '<img src="/js/easyui/themes/icons/pencil.png" style="cursor: pointer;" onclick="editUser(\'' + index + '\');"/>&nbsp;&nbsp;&nbsp;';
                        }
                        if (rec.id != rec.tenantId) {
                            str += '<img src="/js/easyui/themes/icons/edit_remove.png" style="cursor: pointer;" onclick="deleteUser(' + rec.id + ');"/>';
                        }
                        else {
                            str += '';
                        }
                        return str;
                    }
                },
                {title: '登录名称', field: 'loginName', width: 80},
                {title: '用户姓名', field: 'username', width: 80, align: "center"},
                {title: '职位', field: 'position', width: 115, align: "center"},
                {title: '部门', field: 'orgAbr', width: 115, align: "center"},
                {title: '电子邮箱', field: 'email', width: 150, align: "center"},
                {title: '电话号码', field: 'phonenum', width: 150, align: "center"},
                {title: '用户排序', field: 'userBlngOrgaDsplSeq', width: 80, align: "center"},
                {title: '描述', field: 'description', width: 130},
                {field: 'orgaId',hidden:true, width: 10}
            ]],
            toolbar: [
                {
                    id: 'addUser',
                    text: '增加',
                    iconCls: 'icon-add',
                    handler: function () {
                        addUser();
                    }
                },'-',
                {
                    id: 'deleteUser',
                    text: '删除',
                    iconCls: 'icon-remove',
                    handler: function () {
                        batDeleteUser();
                    }
                }
            ],
            onLoadError: function () {
                $.messager.alert('页面加载提示', '页面加载异常，请稍后再试！', 'error');
                return;
            }
        });
        dgResize();
        showUserDetails(1, initPageSize);
    }

    //初始化键盘enter事件
    $(document).keydown(function (event) {
        //兼容 IE和firefox 事件
        var e = window.event || event;
        var k = e.keyCode || e.which || e.charCode;
        //兼容 IE,firefox 兼容
        var obj = e.srcElement ? e.srcElement : e.target;
        //绑定键盘事件为 id是指定的输入框才可以触发键盘事件 13键盘事件
        if (k == "13" && (obj.id == "username" || obj.id == "department" || obj.id == "phonenum"
                || obj.id == "email" || obj.id == "description" || obj.id == "position")) {
            $("#saveusername").click();
        }

        //搜索按钮添加快捷键
        if (k == "13" && (obj.id == "searchUsername" || obj.id == "searchLoginName" || obj.id == "searchPhonenum"
                || obj.id == "searchPosition" || obj.id == "searchEmail" || obj.id == "searchDesc" || obj.id == "searchDept")) {
            $("#searchBtn").click();
        }
    });

    //分页信息处理
    function ininPager() {
        try {
            var opts = $("#tableData").datagrid('options');
            var pager = $("#tableData").datagrid('getPager');
            pager.pagination({
                onSelectPage: function (pageNum, pageSize) {
                    opts.pageNumber = pageNum;
                    opts.pageSize = pageSize;
                    pager.pagination('refresh',
                        {
                            pageNumber: pageNum,
                            pageSize: pageSize
                        });
                    showUserDetails(pageNum, pageSize);
                }
            });
        }
        catch (e) {
            $.messager.alert('异常处理提示', "分页信息异常 :  " + e.name + ": " + e.message, 'error');
        }
    }

    //删除用户信息
    function deleteUser(userID) {
        $.messager.confirm('删除确认', '确定要删除此用户信息吗？', function (r) {
            if (r) {
                $.ajax({
                    type: "post",
                    url: "/user/deleteUser",
                    dataType: "json",
                    data: ({
                        ids: userID
                    }),
                    success: function (res) {
                        if(res && res.code != 200) {
                            $.messager.alert('提示', res.msg, 'error');
                            return;
                        }
                        $.messager.alert('提示', res.msg, 'info');
                        $("#searchBtn").click();
                    },
                    //此处添加错误处理
                    error: function () {
                        $.messager.alert('删除提示', '删除用户信息异常，请稍后再试！', 'error');
                        return;
                    }
                });
            }
        });
    }

    //批量删除用户
    function batDeleteUser() {
        var row = $('#tableData').datagrid('getChecked');
        if (row.length == 0) {
            $.messager.alert('删除提示', '没有记录被选中！', 'info');
            return;
        }
        if (row.length > 0) {
            $.messager.confirm('删除确认', '确定要删除选中的' + row.length + '条用户信息吗？', function (r) {
                if (r) {
                    var ids = "";
                    for (var i = 0; i < row.length; i++) {
                        if (i == row.length - 1) {
                            ids += row[i].id;
                            break;
                        }
                        ids += row[i].id + ",";
                    }
                    if(row[i].loginame == "jsh"){
                        $.messager.alert('提示', '租户jsh不能删除！', 'warning');
                        return;
                    } else if(row[i].id == row[i].tenantId) {
                        $.messager.alert('提示', '不能删除自己！', 'warning');
                        return;
                    } else {
                        $.ajax({
                            type: "post",
                            url: "/user/batchDeleteUser",
                            dataType: "json",
                            async: false,
                            data: ({
                                ids: ids,
                            }),
                            success: function (res) {
                                if(res && res.code != 200) {
                                    $.messager.alert('提示', res.msg, 'error');
                                    return;
                                }
                                $.messager.alert('提示', res.msg, 'info');
                                $("#searchBtn").click();
                                $(":checkbox").attr("checked", false);
                            },
                            //此处添加错误处理
                            error: function () {
                                $.messager.alert('删除提示', '删除用户信息异常，请稍后再试！', 'error');
                                return;
                            }
                        });
                    }
                }
            });
        }
    }

    //增加用户
    var url;
    var userID = 0;

    function addUser() {
        if(checkPower()){
            return;
        }
        $('#userDlg').dialog('open').dialog('setTitle', '<img src="/js/easyui/themes/icons/edit_add.png"/>&nbsp;增加用户');
        $(".window-mask").css({width: webW, height: webH});
        $('#usernameFM').form('clear');
        var row = {};
        $('#usernameFM').form('load', row);
        $("#username").focus();
        $("#loginame").removeAttr("readonly");
        userID = 0;
        /**机构选择*/
        $("#selectType").val("org");
        url = '/user/addUser';
    }

    //重置用户密码
    $("#resetPwd").off("click").on("click", function () {
        $.messager.confirm('重置用户密码', '确定重置该用户的密码为123456吗？', function (r) {
            if (r) {
                $.ajax({
                    type: "post",
                    url: "/user/resetPwd",
                    dataType: "json",
                    data: ({
                        id: userID
                    }),
                    success: function (res) {
                        if (res && res.code === 200) {
                            $.messager.alert('提示', '重置密码成功', 'info');
                        }
                    },
                    //此处添加错误处理
                    error: function () {
                        $.messager.alert('提示', '重置密码失败，请稍后再试！', 'error');
                        return;
                    }
                });
            }
        });
    });

    //保存用户信息
    $("#saveusername").off("click").on("click", function () {
        if(!$('#usernameFM').form('validate')){
            return;
        }
        else {
            /**
             * 2019-03-12
             * 此处用户名和登录名是否重复的校验在保存操作时处理
             * */
            var reg = /^([0-9])+$/;
            var phonenum = $.trim($("#phonenum").val());
            if (phonenum.length > 0 && !reg.test(phonenum)) {
                $.messager.alert('提示', '电话号码只能是数字', 'info');
                $("#phonenum").val("").focus();
                return;
            }
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                data: {
                    info: JSON.stringify($("#usernameFM").serializeObject())
                },
                success: function (res) {
                    if (res && res.code != 200) {
                        $.messager.alert('提示', res.msg, 'error');
                        return;
                    }
                    $('#userDlg').dialog('close');
                    //加载完以后重新初始化
                    var opts = $("#tableData").datagrid('options');
                    showUserDetails(opts.pageNumber, opts.pageSize);
                },
                //此处添加错误处理
                error: function () {
                    $.messager.alert('提示', '网络异常，请稍后再试！', 'error');
                    return;
                }
            });
        }
    });

    //编辑用户信息
    function editUser(index) {
        var rowsdata = $("#tableData").datagrid("getRows")[index];
        var row = {
            username: rowsdata.username,
            loginName: rowsdata.loginName,
            position: rowsdata.position,
            email: rowsdata.email,
            phonenum: rowsdata.phonenum,
            description: rowsdata.description,
            orgAbr: rowsdata.orgAbr,
            orgaId: rowsdata.orgaId,
            orgaUserRelId: rowsdata.orgaUserRelId,
            userBlngOrgaDsplSeq: rowsdata.userBlngOrgaDsplSeq
        };
        $('#userDlg').dialog('open').dialog('setTitle', '<img src="/js/easyui/themes/icons/pencil.png"/>&nbsp;编辑用户信息');
        $(".window-mask").css({width: webW, height: webH});
        $('#usernameFM').form('load', row);
        userID = rowsdata.id;
        //焦点在名称输入框==定焦在输入文字后面
        $("#username").val("").focus().val(rowsdata.username);
        $("#loginName").textbox('textbox').attr('readonly',true);  //设置输入框为禁用
        /**机构选择*/
        $("#selectType").val("org");
        url = '/user/updateUser?id=' + rowsdata.id;
    }


    //搜索处理
    $("#searchBtn").unbind().bind({
        click: function () {
            showUserDetails(1, initPageSize);
            var opts = $("#tableData").datagrid('options');
            var pager = $("#tableData").datagrid('getPager');
            opts.pageNumber = 1;
            opts.pageSize = initPageSize;
            pager.pagination('refresh',
                {
                    pageNumber: 1,
                    pageSize: initPageSize
                });
        }
    });

    function showUserDetails(pageNo, pageSize) {
        var userName = $.trim($("#searchUsername").val());
        var loginName = $.trim($("#searchLoginName").val());
        $.ajax({
            type: "get",
            url: "/user/list",
            dataType: "json",
            data: ({
                search: JSON.stringify({
                    userName: userName,
                    loginName: loginName
                }),
                currentPage: pageNo,
                pageSize: pageSize
            }),
            success: function (res) {
                if(res && res.code === 200){
                    if(res.data && res.data.page) {
                        $("#tableData").datagrid('loadData', res.data.page);
                    }
                }
            },
            //此处添加错误处理
            error: function () {
                $.messager.alert('查询提示', '查询数据后台异常，请稍后再试！', 'error');
                return;
            }
        });
    }

    //重置按钮
    $("#searchResetBtn").unbind().bind({
        click: function () {
            $("#searchUsername").textbox("setValue","");
            $("#searchLoginName").textbox("setValue","");
            $("#searchPhonenum").textbox("setValue","");
            $("#searchPosition").textbox("setValue","");
            $("#searchDept").textbox("setValue","");
            $("#searchEmail").textbox("setValue","");
            $("#searchDesc").textbox("setValue","");
            //加载完以后重新初始化
            $("#searchBtn").click();
        }
    });

    //分配角色
    $('#btnSetRole').click(function () {
        var currentRow = $("#tableData").datagrid("getSelected");
        if (currentRow == null) {
            $.messager.alert('提示',"请选择一条数据再操作！",'warning');
            return false;
        }
        if (currentRow.id == currentRow.tenantId) {
            $.messager.alert('提示',"不能给自己配置角色！",'warning');
            return false;
        }
        this.href = "/pages/user/userRole.html?id=" + currentRow.id;
    });

    //分配部门
    $('#btnSetDepart').click(function () {
        var currentRow = $("#tableData").datagrid("getSelected");
        if (currentRow == null) {
            $.messager.alert('提示',"请选择一条数据再操作！",'warning');
            return false;
        }
        this.href = "/pages/user/userDepot.html?id=" + currentRow.id;
    });

    //分配客户
    $('#btnSetCustomer').click(function () {
        var currentRow = $("#tableData").datagrid("getSelected");
        if (currentRow == null) {
            $.messager.alert('提示',"请选择一条数据再操作！",'warning');
            return false;
        }
        this.href = "/pages/user/userCustomer.html?id=" + currentRow.id;
    });
    /**
     * 用户选择机构
     * */
    $("#lookForSelectOrganization").on("click", function () {
        $('#forSelectOrganizationDlg').dialog({
            title: '机构选择',
            width: webW/2,
            height: webH/2,
            closed: false,
            cache: false,
            href: '/pages/manage/organization_forselect.html',
            modal: true,
            resizable:true
        });
    });
</script>
</body>
</html>